package zk.tool.handler;

import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zk.tool.ZKClient;
import zk.tool.model.TreeItemData;
import zk.tool.ui.AppController;
import zk.tool.ui.UIManager;
import zk.tool.util.AlertUtil;

public class TreeClickHandler implements EventHandler<MouseEvent> {
    private static final Logger log = LoggerFactory.getLogger(TreeClickHandler.class);


    @Override
    public void handle(MouseEvent event) {
        Object source = event.getSource();
        if (!(source instanceof TreeView)) {
            return;
        }
        TreeView<TreeItemData> treeView = (TreeView<TreeItemData>) source;
        TreeItem<TreeItemData> item = treeView.getSelectionModel().getSelectedItem();
        if (item == null) {
            return;
        }

        TreeItemData itemData = item.getValue();
        if (itemData == null) {
            return;
        }

        AppController controller = UIManager.getInstance().getController(AppController.class);
        if (itemData.isDataLoaded()) {
            controller.setSelectedItemData(itemData);
            return;
        }
        synchronized (item) {
            if (controller == null) {
                return;
            }
            if (itemData.isDataLoaded()) {
                // 展示信息
                controller.setSelectedItemData(itemData);
                return;
            }
            ZKClient client = controller.getClient();
            if (client == null) {
                return;
            }

            try {
                // 显示加载中
                controller.setDataTextAreaContent("加载中...");
                // 获取数据
                TreeItemData data = client.getData(itemData.getPath());
                log.info("load {} data success: {}", itemData.getPath(), data);
                itemData.setData(data.getData());
                itemData.setStat(data.getStat());
                itemData.setDataLoaded(true);
                // 信息面板展示信息
                controller.setSelectedItemData(itemData);
            } catch (Exception e) {
                Platform.runLater(() -> {
                    AlertUtil.exception("加载数据失败", e);
                });
                log.error("load data exception: ", e);
            }
        }
    }
}
